<template>
  <el-dialog
    width="500px"
    title="员工导入"
    :visible.sync="showExcelDialog"
  >
    <el-row type="flex" justify="center">
      <div class="upload-excel">
        <input
          ref="excel-upload-input"
          class="excel-upload-input"
          type="file"
          accept=".xlsx, .xls"
          @change="uploadChange"
        >
        <div class="drop">
          <i class="el-icon-upload" />
          <el-button type="text" @click="dwdTpl">下载导入模板</el-button>
          <span>将文件拖到此处或
            <el-button type="text" @click="$refs['excel-upload-input'].click()">点击上传</el-button>
          </span>
        </div>
      </div>
    </el-row>
    <el-row type="flex" justify="end">
      <el-button size="mini" type="primary" @click="showExcelDialog=false">取消</el-button>
    </el-row>
  </el-dialog>
</template>
<script>
import { downloadEmployeeApi, uploadEmployeeApi } from '@/api/employee'
import FileSaver from 'file-saver'
export default {
  data() {
    return {
      showExcelDialog: false
    }
  },
  methods: {
    async dwdTpl() {
      const res = await downloadEmployeeApi()
      FileSaver.saveAs(res, '员工信息表.xlsx') // 下载文件
    },
    // 文件发生变化
    async uploadChange(event) {
    //   console.log(event.target.files)
      // 文件列表
      if (event.target.files.length === 0) {
        return
      }
      // 获取excel文件
      const file = event.target.files[0]
      // console.log(file)
      // 文件上传操作都要用到FormData实例
      const fd = new FormData()
      // fd.append('键 ,文件信息）
      fd.append('file', file)
      // 发生上传请求
      try {
        await uploadEmployeeApi(fd)
        this.$message.success('传入成功')
        this.showExcelDialog = false
        this.$emit('updateList')
      } catch (error) {
        console.log(error)
      } finally {
        // 清空，这样如果下次再选择同样的文件，依然触发change上传
        this.$refs['excel-upload-input'].value = ''
      }
    }
  }
}
</script>

<style scoped lang="scss">
    .upload-excel {
      display: flex;
      justify-content: center;
      margin: 20px;
      width: 360px;
      height: 180px;
      align-items: center;
      color: #697086;
      .excel-upload-input {
        display: none;
        z-index: -9999;
      }
      .btn-upload,
      .drop {
        border: 1px dashed #dcdfe6;
        width: 100%;
        height: 100%;
        text-align: center;
        line-height: 160px;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        justify-content: center;
      }
      .drop {
        line-height: 40px;
        color: #bbb;
        i {
          font-size: 60px;
          display: block;
          color: #c0c4cc;
        }
      }
    }
</style>
